package com.example.demo.controller;

import com.example.demo.pojo.Result;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 作者：邓利
 * 时间：2024-06-03
 **/
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public User login(@RequestBody User user) {
        User dbUser = userService.getUserByNameAndPassword(user.getUsername(), user.getPassword());
        if (dbUser != null) {
            return dbUser;
        } else {
            return null;
        }
    }

    /**
     * 登录成功
     *
     * @param user
     * @return ，生成token
     */
    @GetMapping("/login1")
    public User login1(User user) {
        String username = "admin";
        String password = "123456";
        if (username.equals(user.getUsername()) && password.equals(user.getPassword())) {
            //创建Token:token保存到user对象

            user.setToken(JwtUtil.createToken());
            return user;
        }
        return null;
    }

    /**
     * 查看Token是滞过期
     */
//    @GetMapping("/check_token")
//    public boolean checkToken(String token) {
//        return JwtUtil.checkToken(token);
//    }

    /**
     * 这个方法是放在请求头
     */
    @GetMapping("/check_token")
    public boolean checkToken(HttpServletRequest request) {
        String token= request.getHeader("token");//key->token
        return JwtUtil.checkToken(token);
    }


}
